import { FunctionComponent, useEffect } from 'react';
import { Button, Checkbox, Form, Input, Space } from 'antd';
import { OptionType, QuestionCheckboxPropsType } from './interface';
import useQuestionStore from '../../../zustandStore/questionStore';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';
import { nanoid } from 'nanoid';
import { v4 as uuidv4 } from 'uuid';
const PropComponent: FunctionComponent<QuestionCheckboxPropsType> = (props: QuestionCheckboxPropsType) => {
  const setComponents = useQuestionStore((state) => state.setComponents);
  const { disabled, title, isVertical, list } = props;
  const [form] = Form.useForm();
  //监听切换组件重新给form赋值
  useEffect(() => {
    form.setFieldsValue({ title, isVertical, list });
  }, [title, isVertical, list]);
  //改变form字段的值触发整个组件进行更新
  //form.list里面的form.item改变后，会出现问题，options里面的其他选项会被覆盖
  const hanlerValueChange = debounce((changedValues: Record<string, any>) => {
    console.log(11);
    if (Object.prototype.hasOwnProperty.call(changedValues, 'list')) {
      const valueByList = form.getFieldsValue().list;
      valueByList.forEach((o: OptionType) => {
        if (!o.value) o.value = uuidv4();
      });
      setComponents({ list: valueByList });
    } else {
      setComponents(changedValues);
    }
  }, 100);
  return (
    <Form
      onValuesChange={hanlerValueChange}
      form={form}
      disabled={disabled}
      layout="vertical"
      initialValues={{ disabled, title, isVertical, list }}>
      <Form.Item name="title" label="问卷标题" rules={[{ required: true, message: '请输入段落内容' }]}>
        <Input />
      </Form.Item>
      <Form.List name="list">
        {(fields, { add, remove }) => (
          <>
            {fields.map((o, index) => (
              <Space key={o.key} align="baseline">
                {/* {name传递数组，因为只有‘text’无法确定其具体位置,o.name定位options的第几项} */}
                <Form.Item name={[o.name, 'checked']} valuePropName="checked">
                  <Checkbox></Checkbox>
                </Form.Item>
                <Form.Item
                  name={[o.name, 'text']}
                  validateTrigger={['onChange', 'onBlur']}
                  rules={[
                    { required: true, message: '请输入选项内容' },
                    {
                      validator: (_, text) => {
                        const { list } = form.getFieldsValue();
                        let num = 0;
                        list.forEach((o: OptionType) => {
                          if (o.text === text) {
                            num++;
                          }
                        });
                        if (num === 1) return Promise.resolve();
                        return Promise.reject(new Error('选项内容不能重复'));
                      },
                    },
                  ]}>
                  <Input placeholder="请输入选项文字" />
                </Form.Item>
                {index > 0 && <MinusCircleOutlined onClick={() => remove(o.name)} />}
              </Space>
            ))}
            <Form.Item>
              <Button
                block
                type="link"
                onClick={() => add({ value: '', text: '', checked: false })}
                icon={<PlusOutlined />}>
                添加选项
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item name="isVertical" valuePropName="checked">
        <Checkbox>水平/竖向排列</Checkbox>
      </Form.Item>
    </Form>
  );
};

export default PropComponent;
